package com.tledu.publisher.service;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SendService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    public String send(String exchangeName, String message) {
        // 发送消息
        //将message去掉后五个字符
        message = message.substring(0, message.length() - 5);
        //将message以逗号分割并放入字符串数组
        String[] messages = message.split(",");
        //拿到messages中redis里不存在的key值放入finalmsg中
        List<String> finalmsg =new ArrayList<>();
        for (String msg : messages) {
            if (!redisTemplate.hasKey(msg)) {
                finalmsg.add(msg);
            }
        }
        if (finalmsg.size() > 0){
            //将finalmsg中的字符串以逗号拼接并拼接上"数据有报错"发送到rabbitmq
            String joinedMessage = String.join(",", finalmsg);
            String message1 = joinedMessage + "数据有报错";
            System.out.println("发送给交换机的message为:"+message1);
            rabbitTemplate.convertAndSend(exchangeName, "", message1);
            return "发送成功";
        }
        return "没有新错误";
    }
}